//
//  AppDelegate+MsgPush.m
//  New_Runway
//
//  Created by 邢毅 on 2018/5/7.
//  Copyright © 2018年 NelsonJ. All rights reserved.
//

#import "AppDelegate+MsgPush.h"
//#import <JPUSHService.h>
#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#import <UserNotifications/UserNotifications.h>
#endif
#import "NRWCarPushMsgModel.h"
#import "NRWCarNavigationController.h"
#import "NRWCarNotificationVC.h"
#import <CWAuctionSDK/CWAuctionSDK.h>
#import "UserDetailModel.h"
#import "NRWCarNavigationView.h"

#import <objc/runtime.h>

@implementation AppDelegate (MsgPush)

#pragma mark - init
-(void)initJpushWithLaunchOptions:(NSDictionary *)launchOptions{
    JPUSHRegisterEntity * entity = [[JPUSHRegisterEntity alloc] init];
    entity.types = JPAuthorizationOptionAlert|JPAuthorizationOptionBadge|JPAuthorizationOptionSound;
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
        
    }
    [JPUSHService registerForRemoteNotificationConfig:entity delegate:self];
    
    [JPUSHService setupWithOption:launchOptions appKey:getJPushAppKey()
                          channel:channel
                 apsForProduction:isProduction
            advertisingIdentifier:nil];
    [JPUSHService registrationIDCompletionHandler:^(int resCode, NSString *registrationID) {
        if(resCode == 0){
            [self addloginStatusObserver];
            NSLog(@"registrationID获取成功：%@",registrationID);
            
        }
        else{
            NSLog(@"registrationID获取失败，code：%d",resCode);
        }
    }];
    
    if (launchOptions[UIApplicationLaunchOptionsRemoteNotificationKey]) {
        
        [self jpushDistributionWithDict:launchOptions[UIApplicationLaunchOptionsRemoteNotificationKey] isTouchPush:YES];
    }
}

#pragma mark - loginObserver
- (void)addloginStatusObserver {
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(userloginSuccess) name:loginSuccessKey object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(userLogOutSuccess) name:logOutKey object:nil];
}

- (void)userloginSuccess {
    
    NSMutableSet *tagSet = [NSMutableSet set];
    NSString *userId = [NRWCarUser sharedUser].userId;
    NSString *marketId = [NRWCarUser sharedUser].marketId;
    NSString *shopId = [NRWCarUser sharedUser].shopId;
    
    if (marketId.length > 0) {
        [tagSet addObject:marketId];
    }
    
    if (shopId.length > 0) {
        [tagSet addObject:shopId];
        [tagSet addObject:@"shopUser"];
    }
    
    [JPUSHService setTags:tagSet.copy completion:^(NSInteger iResCode, NSSet *iTags, NSInteger seq) {
        
    } seq:0];
    
    if (userId.length > 0) {
        
        [JPUSHService setAlias:userId completion:^(NSInteger iResCode, NSString *iAlias, NSInteger seq) {
            
        } seq:0];
    }
    
}

- (void)userLogOutSuccess {
    
    [JPUSHService deleteAlias:^(NSInteger iResCode, NSString *iAlias, NSInteger seq) {
        
    } seq:0];
    
    [JPUSHService cleanTags:^(NSInteger iResCode, NSSet *iTags, NSInteger seq) {
        
    } seq:0];
}

#pragma mark - pushDelegate
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    NSLog(@"%@", [NSString stringWithFormat:@"Device Token: %@", deviceToken]);
    [JPUSHService registerDeviceToken:deviceToken];
}
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    NSLog(@"did Fail To Register For Remote Notifications With Error: %@", error);
}

#pragma mark- JPUSHRegisterDelegate
#ifdef NSFoundationVersionNumber_iOS_9_x_Max
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler  API_AVAILABLE(ios(10.0)){
    // Required
    NSDictionary * userInfo = notification.request.content.userInfo;
    
    if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
        
        [self jpushDistributionWithDict:userInfo isTouchPush:NO];
    }
    completionHandler(UNNotificationPresentationOptionAlert); // 需要执行这个方法，选择是否提醒用户，有Badge、Sound、Alert三种类型可以选择设置
}
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)(void))completionHandler  API_AVAILABLE(ios(10.0)){
    // Required
    NSDictionary * userInfo = response.notification.request.content.userInfo;
    
    if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
        
        [self jpushDistributionWithDict:userInfo isTouchPush:YES];
    }
    completionHandler();  // 系统要求执行这个方法
}

#endif
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    
    // Required, iOS 7 Support
    [JPUSHService handleRemoteNotification:userInfo];
    
    if (application.applicationState == UIApplicationStateActive) {//在前台
        
        NRWCarNavigationController *nav = (NRWCarNavigationController *)[UIApplication sharedApplication].keyWindow.rootViewController;
        
        if ([nav.topViewController isKindOfClass:NSClassFromString(@"NRWCarNotificationVC")]) {
            
            UIViewController *vc = nav.topViewController;
            
            [vc performSelector:@selector(reloadData)];
        }
    }
    
    completionHandler(UIBackgroundFetchResultNewData);
}

#pragma mark - publicMethod
- (void)setPushBage:(NSInteger)bage {
    
    [JPUSHService setBadge:bage];
}

#pragma mark - privateMethod
/**
 根据 推送userInfo 统一处理事件

 @param dict userInfo
 @param isTouchPush 是否点击了通知条
 */
- (void)jpushDistributionWithDict:(NSDictionary *)dict isTouchPush:(BOOL)isTouchPush {
    
    NSString *type = dict[@"type"];
    
    if (!isEmptyOrNilString(type)) {//如果type有值, 不是系统消息推送
        
        if ([type isEqualToString:@"carWin"]) {//车赢
            
            if (!isTouchPush) {
                return;
            }
            
            [self setPushUserInfo:dict];
            
            [self turnToCarWin];
        }
    } else {
        
        [NRWCarPushMsgModel addNewModelWithUserInfo:dict];
        
        if (isTouchPush) {
            
            [self turnToNotificationVC];
        }
    }
}

- (void)turnToCarWin {
    
    [self loadUserInfo];
}

- (void)turnToNotificationVC {
    
    if ([NRWCarUser sharedUser].didLogin == NO) {
        return;
    }
    
    [self needReloadPushMessageVCData];
}

- (void)needReloadPushMessageVCData {
    
    NRWCarNavigationController *nav = (NRWCarNavigationController *)[UIApplication sharedApplication].keyWindow.rootViewController;
    
    //如果当前页面就是 通知vc, 直接刷新数据
    if ([nav.topViewController isKindOfClass:NSClassFromString(@"NRWCarNotificationVC")]) {
        
        UIViewController *vc = nav.topViewController;
        
        [vc performSelector:@selector(reloadData)];
        
        return;
    }
    
    //如果当前视图堆栈里面有 通知vc  直接跳回去并刷新数据
    for (UIViewController *vc in nav.viewControllers) {
        
        if ([vc isKindOfClass:NSClassFromString(@"NRWCarNotificationVC")]) {
            
            [nav popToViewController:vc animated:YES];
            
            [vc performSelector:@selector(reloadData)];
            
            return;
        }
    }
    
    //如果都没有   创建一个跳过去
    [nav pushViewController:[NRWCarNotificationVC new] animated:YES];
}

#pragma mark - carWin
-(void)loadUserInfo{
    NSString *url = [NSString stringWithFormat:@"%@%@",Api,UserInfoApi];
    [SVProgressHUD show];
    [YQNetworking postWithUrl:url refreshRequest:YES cache:NO params:@{@"userId":[NRWCarUser sharedUser].userId} progressBlock:^(int64_t bytesRead, int64_t totalBytes) {
        
    } successBlock:^(id response) {
        UserDetailModel *model = [UserDetailModel mj_objectWithKeyValues:response];
        if (model.code == 1) {
            
            [self carWinLogin:model];
        }
        [SVProgressHUD dismiss];
        
    } failBlock:^(NSError *error) {
        [SVProgressHUD dismiss];
        [ShowMessage showHintMessage:@"请求失败!" duration:2.0 withRemindId:remindFail];
    }];
    
    
}

-(void)carWinLogin:(UserDetailModel *)model {
    
    MJWeakSelf
    
    [CWAuctionInterface syncUserMessageWithMobile:model.result.userMobile realityName:model.result.userName isCanAuction:model.result.shop.shopAuctionState operateCityName:model.result.market.city.cityName detailedAddress:model.result.shop.shopAddress isProduction:isProduct result:^(BOOL status, NSError *error) {
        
        NSDictionary *dict = [weakSelf pushUserInfo];
        
        UIViewController *vc = [CWAuctionInterface getMessageToShowAuctionInfoWithPid:[dict[@"pid"] integerValue] pushMessageTypeID:[dict[@"typeId"] integerValue]];
        NRWCarNavigationView *navView = [[NRWCarNavigationView alloc] initWithController:vc andTitle:dict[@"title"] andStyle:navgationStyle_deepColor];
        
        if (Screen_height == 812) {
            navView.frame = CGRectMake(0, 0, Screen_width, 84);
        } else {
            navView.frame = CGRectMake(0, 0, Screen_width, 64);
        }
        
        [vc.view addSubview:navView];
        
        if ([((NRWCarNavigationController *)weakSelf.window.rootViewController).topViewController isKindOfClass:[vc class]]) {
            return;
        }
        
        [((NRWCarNavigationController *)weakSelf.window.rootViewController) pushViewController:vc animated:YES];
        
    }];
    
#pragma mark - 建立socket 连接
    [CWAuctionInterface startServiceConnect];
}

/**< 根据 bundleID 获取极光推送AppKey */
NSString *getJPushAppKey() {
    
    NSString *bundleID = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleIdentifier"];
    
    if ([bundleID hasSuffix:@"bete"]) {
        return @"a1332c74a901feb2b7d0252b";
    } else {
        return @"86a654c40c0012804e1d3885";
    }
}

#pragma mark - setter
- (void)setPushUserInfo:(NSDictionary *)pushUserInfo {
    objc_setAssociatedObject(self, @"pushUserInfo", pushUserInfo, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

#pragma mark - getter
- (NSDictionary *)pushUserInfo {
    return objc_getAssociatedObject(self, @"pushUserInfo");
}

@end
